package org.csu.gp_store.controller;

import org.csu.gp_store.bo.BrowsingHistoryBO;
import org.csu.gp_store.common.CommonResponse;
import org.csu.gp_store.entity.BrowsingHistory;
import org.csu.gp_store.service.BrowsingHistoryService;
import org.csu.gp_store.service.ProductService;
import org.csu.gp_store.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/browsing")
public class BrowsingHistoryController {
    @Autowired
    private BrowsingHistoryService browsingHistoryService;

    @Autowired
    private ProductService productService;

    @GetMapping("/histories")
    @ResponseBody
    public CommonResponse<List<BrowsingHistoryBO>> getBrowsingHistoryBOByAccountID(@RequestHeader("MyToken") String MyToken){
        if (null ==MyToken ||"".equals(MyToken)){
            return CommonResponse.createForError("身份验证失败，请登陆后再试！");
        }
        String accountID= TokenUtil.getUserIdByToken(MyToken);
        if (null==accountID||"".equals(accountID)){
            return CommonResponse.createForError("身份验证失败，请登陆后再试！");
        }
        try {
            List<BrowsingHistory> browsingHistoryList=browsingHistoryService.getBrowsingHistoryByAccountID(Long.valueOf(accountID));
            List<BrowsingHistoryBO>browsingHistoryBOList=new ArrayList<>();
            BrowsingHistory browsingHistory;
            for (int i =browsingHistoryList.size()-1;i>=0;i--){
                browsingHistory=browsingHistoryList.get(i);
                browsingHistoryBOList.add(BrowsingHistoryBO.toBrowsingHistoryBO(
                        productService.getProductByProductID(browsingHistory.getProductID()),browsingHistory
                ));
            }
            return CommonResponse.createForSuccess(browsingHistoryBOList);
        }catch (Exception e){
            e.printStackTrace();
        }
        return CommonResponse.createForError("出现未知错误，请稍后重试！");
    }

    @PostMapping("/histories/insert")
    @ResponseBody
    public void insertBrowsingHistory(@RequestHeader("MyToken") String MyToken,
                                      @RequestParam("productID")String productID){
        String accountID= TokenUtil.getUserIdByToken(MyToken);
        try {
            assert accountID != null;
            browsingHistoryService.deleteBrowsingHistory(Long.valueOf(accountID),Long.valueOf(productID));
            browsingHistoryService.insertBrowsingHistory(Long.valueOf(accountID),Long.valueOf(productID));
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
